<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <!--双向绑定 如果输入 keyword就有值-->
          <el-input v-model="keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--分页数据列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="80" align="center">
      </el-table-column>
      <el-table-column type="index" width="80" align="center">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="130" align="center">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="130" align="center">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="130" sortable align="center">
        <template scope="scope">
          <span style="color: #13ce66" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="130" align="center">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="130" align="center">
        <template scope="scope">
          <span style="color: darkorange" v-if="scope.row.parent">{{ scope.row.parent.name }}</span>
          <span style="color: gray" v-else>无上级部门</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页栏数据-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="totals" style="float:right;" :current-page="currentPage">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
              <!--
                下拉框显示:
                v-for="item in managers" + 2个span
                回显机制:
                先根据v-model="saveForm.manager_id"中的manager_id"找到回显哪一个对象
                但是对象中有很多属性再通过label="item.username" - 回显对象的username
                传值机制:
                  1.当你选中某一个部门经理的时候,:value="item.id" 它会把选中对象的的id
                  2.赋值给v-model="saveForm.manager_id"这个中的manager_id
              -->
            <el-select v-model="saveForm.manager_id" placeholder="请选择">
              <el-option
                  v-for="item in managers"
                  :label="item.username"
                  :value="item.id">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone}}</span>
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-input v-model="saveForm.parent_id" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getUserListPage, removeUser, batchRemoveUser, saveUser, addUser} from '../../api/api';

export default {
/*-------------------------------------------------------------------------------------------------*/

  data() {
    return {
      departments: [],    //分页相关数据模型
      totals: 0,          //后端数据个数,vue需要它做分页栏计算
      currentPage: 1,     //当前页,默认值为1
      pageSize: 5,        //每页条数,默认值为5
      listLoading: false, //加载圈默认false
      keyword: '',        //高级查询的数据,不填写默认空串,后端会动态判断拼接
      sels: [],           //列表选中列 将选中列的对象id装入该数组传给后端
      title: '',          //动态标题,根据场景赋值
      saveFormVisible: false,//对话框显示,默认false,单击时触发变true显示
      saveLoading: false, //加载圈,提交单击事件时变true
      managers: [],       //employee的对象数据

      //表单匹配验证,name和sn必须输入值才能继续操作
      saveFormRules: {
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入部门编号', trigger: 'blur'}
        ]
      },

      //编辑界面数据,都给默认值,重置数据方便添加方法,数值类型默认null,字符串默认空串
      saveForm: {
        id: null,
        name: '',
        sn: '',
        state: 1,
        manager_id: null,
        parent_id: null
      },
    }
  },
  /*-------------------------------------------------------------------------------------------------*/
  methods: {
    //1.获取用户列表
    getDepartment() {
      let para = {
        //封装当前分页的数据
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //将高级查询的数据传递给后端,如果没输入就是空串,不会影响分页查询,后端会if判断
        keyword: this.keyword,
      };
      //将加载圈显示出来
      this.listLoading = true;
      //发送异步请求,将当前页的数据携带给后端进行查询  res是返回的数据
      this.$http.post("/department", para).then(res => {
        //将回调函数里面的数据赋给当前分页的数据
        this.totals = res.data.totals;
        this.departments = res.data.data;
        //显示完毕将加载圈消失
        this.listLoading = false;
      }).catch(res => {
        //异常显示提示框
        this.$message.error("网络繁忙,请稍后再试...")
      })
    },

    //2.分页栏获取值跳转
    handleCurrentChange(val) {
      //将每次点击的页赋值当前页,然后再调分页方法
      this.currentPage = val;
      this.getDepartment();
    },

    //3.高级查询
    keywordQuery() {
      this.currentPage = 1;//赋值为1 查询数据在第一页开始
      this.getDepartment();//调用列表数据展示
    },

    //4.单个删除
    handleDel: function (index, row) {
      //警告提示框
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点击确定进入then方法中
        this.listLoading = true;//开启加载圈
        //发送异步请求,将对象的id传给后端
        this.$http.delete("/department/" + row.id).then(res => {
          if (res.data.success) {  //状态对象如果是true则删除成功进入if
            this.$message.success("删除成功!") //成功提示框
            //算出最后总页数
            var totalPage = Math.ceil(this.totals / this.pageSize);
            //如果当前页是总页数就是最后一页,并且个数模页数可以整除那就是每页最后一条,并且这不是第一页
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              //满足条件就返回到删除页的前一页
              this.currentPage = this.currentPage - 1;
            }
            this.getDepartment();//删除完后调用列表数据展示
            this.listLoading = false;//关闭加载圈
          } else {
            //如果状态对象为false则失败,弹框提醒用户
            this.$message.error("网络繁忙~~请稍后再试..")
          }
        }).catch(() => {  //catch则是有异常 弹窗提醒
          this.$message.error("网络繁忙~~请稍后再试..")
        });
      }).catch(() => {
        //提示框点击取消则弹窗提醒
        this.$message.error("请重新操作..")
      });
    },

    //5.取出当前行对象放入数组
    selsChange: function (sels) {
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)//数组.map获取里面所有的id值成id数组
      this.$confirm('确认删除选中记录吗？', '提示', {
        //警告提示框
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //发送异步请求将id数组传入给后端
        this.$http.patch("/department", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) { //状态对象true则删除成功
            this.$message.success("删除成功!")//弹框提醒
            this.currentPage = 1;//展示列表数据之前将当前页面改为1
            this.getDepartment();//展示列表数据
          } else {
            this.$message.error("网络繁忙~~请稍后再试..")//状态对象false则弹框提醒
          }
        }).catch(res => {
          this.$message.error("网络繁忙~~请稍后再试..")//代码异常弹窗提醒
        });
      }).catch(() => { //点击取消啥也不提醒
      });
    },

    //7.点击添加弹出对话框
    handleAdd: function () {

      this.title = "添加";  //动态修改标题

      this.saveForm = {   //每次点击将form表单中数据清空
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null,
      };
      this.saveFormVisible = true;  //显示添加对话框
      this.getManagers();           //获取Employee对象
    },

    //8.点击修改按钮弹出对话框
    handleSave: function (index, row) {
      //动态修改标题
      this.title = "修改";
      //回显数据
      //克隆对象防止列表中的数据也发生改变
      this.saveForm = Object.assign({}, row);//按照属性同名原则进行赋值
      //显示对话框
      this.saveFormVisible = true;
      //获取所有的部门经理
      this.getManagers();
    },

    //9.添加或者修改对话框单击事件处理
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => { //valid表单验证 满足条件则true
        if (valid) {
          //必填项都填了则弹窗确认提交框
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start(); 对象克隆,防止model改变原数据
            let para = Object.assign({}, this.saveForm);
            //发送请求将克隆对象传入给后端
            this.$http.put("/department",para).then(res =>{
              this.saveLoading = false; //关闭提交的加载框
              this.saveFormVisible = false; //关闭对话框
              if (res.data.success){  //状态对象 操作成功则进入if
                this.$message.success("操作成功!");//弹窗提醒
                this.getDepartment();//添加完成后关闭加载框、对话框并展示列表数据
              }else {
                this.$message.error("系统繁忙,请稍后再试！")//状态对象false 弹窗提醒
              }
            }).catch(res =>{
              //代码错误,弹框提醒
              this.$message.error("系统繁忙,请稍后再试！")
            })
          });
        }
      });
    },

    //10.获取所有的经理对象
    getManagers(){
      this.$http.get("/employee").then(res =>{
          //将所有的员工值赋给managers
          this.managers = res.data;
      })
    }
  },
  /*-------------------------------------------------------------------------------------------------*/

  //钩子方法,页面加载即加载
  mounted() {
    this.getDepartment();
  }
}
</script>

<!--它的 CSS 样式就只能作用于当前的组件-->
<style scoped></style>
